//
//  CommunicationViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-5.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "CommunicationViewController.h"
#import "LeveyTabBarController.h"
#import "NetworkCenter.h"
#import "JXMsgViewController.h"
#import "JXFriendViewController.h"
#import "JXGroupViewController.h"
#import "AppDelegate.h"
#import "RAViewController.h"
#import "RADataObject.h"

//环信Controller
#import "ChatListViewController.h"
//#import "ContactsViewController.h"
#import "SettingsViewController.h"
#import "CoreDataEntity.h"
#import "ApplyViewController.h"
#import "GroupListViewController.h"

#pragma mark - 颜色
#define kNavigationBarColor [UIColor colorWithRed:192.0/255.0 green:57.0/255.0 blue:43.0/255.0 alpha:1]
#define KSPEColor [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1]
#define KBtnTextColor [UIColor colorWithRed:119.0/255.0 green:119.0/255.0 blue:119.0/255.0 alpha:1]

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;

@interface CommunicationViewController ()<UIAlertViewDelegate, IChatManagerDelegate>
{
    UIButton *_friendsBtn;
    UIButton *_groupsBtn;
    UIButton *_addrsBtn;
    UIView  *moveLine;
    NSInteger _btnTag;
    BOOL isRollBack;
    MBProgressHUD * HUD;
    UIActivityIndicatorView *_activityView;
    BOOL isExcute;
    /*分页*/
    UIScrollView * _scrollView;
    UIPageControl * _pageControl;
    BOOL _firstInstall;
    
    CGFloat _width;
    CGFloat _height;
    
    NSManagedObjectContext * _context;
    UIBarButtonItem *_addFriendItem;
}

@property (nonatomic,strong) UIView * indicatorView;
@property (strong, nonatomic)NSDate * lastPlaySoundDate;

@end

@implementation CommunicationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if ([constant checkAccount]) {
        TTAlertNoTitle(@"亲,您是注册用户,现在还不能聊天哦.");
        return;
    }
    
    _btnTag = 1001;
    _width = self.view.frame.size.width;
    _height = self.view.frame.size.height;
    _context = [CoreDataEntity openDB];
    [CoreDataEntity sharedCoreDataEntity].context = _context;
    [self addMovePageLine];
    [self addPageController];
    [self addScrollView];
    [self addView];
//    if (!isExcute) {
//        [self getAddressBookFromLocal];
//        isExcute = YES;
//    }
    [self huanxinSet];
}

#pragma mark 添加移动分页条
-(void)addMovePageLine{
    isRollBack = NO;
    _firstInstall = NO;
    _topBarContainer = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _width, 47)];
    _topBarContainer.backgroundColor = [UIColor whiteColor];
    //灰色的线
    UIView *barLine = [[UIView alloc] initWithFrame:CGRectMake(0, 47, _width, 1)];
    barLine.backgroundColor = KSPEColor;
    
    [_topBarContainer addSubview:barLine];
    _friendsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _friendsBtn.tag = 1003;
    [_friendsBtn setTitle:@"最近" forState:UIControlStateNormal];
    [_friendsBtn setTitleColor:kNavigationBarColor forState:UIControlStateHighlighted];
    [_friendsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];
    [_friendsBtn addTarget:self action:@selector(switchPageVc:) forControlEvents:UIControlEventTouchUpInside];
    _friendsBtn.frame = CGRectMake(2*_width/3, 0, _width/3, 47);
    [_topBarContainer addSubview:_friendsBtn];
    
    _groupsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_groupsBtn setTitle:@"移动三会" forState:UIControlStateNormal];
    _groupsBtn.tag = 1001;
    [_groupsBtn setTitleColor:kNavigationBarColor forState:UIControlStateHighlighted];
    [_groupsBtn addTarget:self action:@selector(switchPageVc:) forControlEvents:UIControlEventTouchUpInside];
    [_groupsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
    _groupsBtn.frame = CGRectMake(0, 0, _width/3, 47);
    [_topBarContainer addSubview:_groupsBtn];
    
    _addrsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addrsBtn setTitle:@"通讯录" forState:UIControlStateNormal];
    _addrsBtn.tag = 1002;
    [_addrsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];
    [_addrsBtn setTitleColor:kNavigationBarColor forState:UIControlStateHighlighted];
    [_addrsBtn addTarget:self action:@selector(switchPageVc:) forControlEvents:UIControlEventTouchUpInside];
    _addrsBtn.frame = CGRectMake(_width/3, 0, _width/3, 47);
    
    [_topBarContainer addSubview:_addrsBtn];
    
    //红条
    moveLine = [[UIView alloc]initWithFrame:CGRectMake(0, 43, _width/3, 4)];
    moveLine.backgroundColor = kNavigationBarColor;
    [_topBarContainer addSubview:moveLine];
    [self.view addSubview:_topBarContainer];
}

#pragma mark 添加视图
-(void)addScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,48,_width ,_height)];
    //3.设置滚动视图的属性
    [_scrollView setBounces:NO];
    [_scrollView setShowsHorizontalScrollIndicator:NO];
    [_scrollView setContentSize:CGSizeMake(3 * _width, _height)];
    //4.允许滚动视图分页显示
    [_scrollView setPagingEnabled:YES];
    // 设置滚动视图的代理
    [_scrollView setDelegate:self];
    [self.view addSubview:_scrollView];
}

-(void)addPageController{
    // 5. 增加分页控件
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    pageControl.backgroundColor = [UIColor redColor];
    // 5.1 设置位置和大小
    [pageControl setBounds:CGRectMake(0, 0, 150.0, 50.0)];
    [pageControl setCenter:CGPointMake(_width / 2, _height)];
    // 5.2 设置页面属性
    [pageControl setNumberOfPages:3];
    [pageControl setCurrentPage:0];
    // 当前页面被选中的标示颜色
    [pageControl setCurrentPageIndicatorTintColor:[UIColor redColor]];
    // 其他页面的标示颜色
    [pageControl setPageIndicatorTintColor:[UIColor blackColor]];
    // 需要监听分页控件的变化
    [pageControl addTarget:self action:@selector(updatePageChanged:) forControlEvents:UIControlEventValueChanged];
    _pageControl = pageControl;
    // 添加到视图
    [self.view addSubview:pageControl];
}

#pragma mark 添加视图
-(void)addView{
    _friendsTableView = [[ChatListViewController alloc]init];
    _groupsTableView = [[GroupListViewController alloc]initWithStyle:UITableViewStylePlain];
    [_friendsTableView.view setFrame:CGRectMake(_width * 2, 0,_width, _scrollView.frame.size.height - 161)];
    [_groupsTableView.view setFrame: CGRectMake(0, 0, _width, _scrollView.frame.size.height - 161)];
    [_addrsTableView.view  setFrame:CGRectMake(_width, -35 , _width, _scrollView.frame.size.height - 126)];
    [_scrollView addSubview:_friendsTableView.view];
    [_scrollView addSubview:_groupsTableView.view];
    [_scrollView addSubview:_addrsTableView.view];
}

#pragma mark - 分页控件的监听方法
- (void)updatePageChanged:(UIPageControl *)pageControl
{
    CGFloat offsetX = pageControl.currentPage * _scrollView.bounds.size.width;
    [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

#pragma mark - 滚动视图代理方法
// 完成减速意味着页面切换完成
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 设置PageControl页数
    NSInteger pageNo = scrollView.contentOffset.x / scrollView.bounds.size.width;

    [self switchPageVc2:pageNo];
}

- (void)switchPageVc2: (NSInteger)pageNo
{
    [_friendsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];
    [_groupsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];
    [_addrsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];

    if(pageNo == 0){
        _btnTag =1001;
        [_groupsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        CGRect frame = CGRectMake(0, 43, self.view.frame.size.width/3, 4);
        [UIView beginAnimations:@"Curl"context:nil];//动画开始
        [UIView setAnimationDuration:0.20];
        [UIView setAnimationDelegate:self];
        [moveLine setFrame:frame];
        [UIView commitAnimations];
    }else if (pageNo == 1){
        _btnTag =1002;
        if (!isExcute) {
            [self getAddressBookFromLocal];
            isExcute = YES;
        }
        CGFloat width = self.view.frame.size.width;
        [_addrsTableView.view  setFrame:CGRectMake(width, -35, width, [[UIScreen mainScreen] bounds].size.height-126)];
        [_scrollView addSubview:_addrsTableView.view];
        [_addrsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        CGRect frame = CGRectMake(width/3, 43, self.view.frame.size.width/3, 4);
        [UIView beginAnimations:@"Curl"context:nil];//动画开始
        [UIView setAnimationDuration:0.20];
        [UIView setAnimationDelegate:self];
        [moveLine setFrame:frame];
        [UIView commitAnimations];
    }else if (pageNo == 2){
        [_friendsTableView.view removeFromSuperview];
        [_scrollView addSubview:_friendsTableView.view];
        _btnTag =1003;
        [_friendsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        CGRect frame = CGRectMake(2*self.view.frame.size.width/3, 43, self.view.frame.size.width/3, 4);
        [UIView beginAnimations:@"Curl"context:nil];//动画开始
        [UIView setAnimationDuration:0.20];
        [UIView setAnimationDelegate:self];
        [moveLine setFrame:frame];
        [UIView commitAnimations];
    }
}

- (void)switchPageVc: (UIButton *)btn
{
//    [_friendsTableView.view removeFromSuperview];
//    [_addrsTableView.view removeFromSuperview];
//    [_groupsTableView.view removeFromSuperview];
//    
//    [_scrollView addSubview:_friendsTableView.view];
//    [_scrollView addSubview:_addrsTableView.view];
//    [_scrollView addSubview:_groupsTableView.view];
    UIButton *nBtn = (UIButton *)btn;
    [_friendsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];
    [_groupsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];
    [_addrsBtn setTitleColor:KBtnTextColor forState:UIControlStateNormal];

    if(nBtn.tag == 1001){
        _btnTag =1001;
        [_pageControl setCurrentPage:0];
        CGFloat offsetX = _pageControl.currentPage * _scrollView.bounds.size.width;
        [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        [_groupsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        CGRect frame = CGRectMake(0, 43, self.view.frame.size.width/3, 4);
        [UIView beginAnimations:@"Curl"context:nil];//动画开始
        [UIView setAnimationDuration:0.40];
        [UIView setAnimationDelegate:self];
        [moveLine setFrame:frame];
        [UIView commitAnimations];
    }else if (nBtn.tag == 1002){
        _btnTag =1002;
        if (!isExcute) {
            [self getAddressBookFromLocal];
            isExcute = YES;
        }
        [_pageControl setCurrentPage:1];
        CGFloat offsetX = _pageControl.currentPage * _scrollView.bounds.size.width;
        [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        CGFloat width = self.view.frame.size.width;
        [_addrsTableView.view  setFrame:CGRectMake(width, -35, width, [[UIScreen mainScreen] bounds].size.height-126)];
        [_scrollView addSubview:_addrsTableView.view];
        [_addrsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        CGRect frame = CGRectMake(width/3, 43, self.view.frame.size.width/3, 4);
        [UIView beginAnimations:@"Curl"context:nil];//动画开始
        [UIView setAnimationDuration:0.40];
        [UIView setAnimationDelegate:self];
        [moveLine setFrame:frame];
        [UIView commitAnimations];
    }else if (nBtn.tag == 1003){
        [_friendsTableView.view removeFromSuperview];
        [_scrollView addSubview:_friendsTableView.view];
        _btnTag =1003;
        
        [_pageControl setCurrentPage:2];
        CGFloat offsetX = _pageControl.currentPage * _scrollView.bounds.size.width;
        [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        [_friendsBtn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        CGRect frame = CGRectMake(2*self.view.frame.size.width/3, 43, self.view.frame.size.width/3, 4);
        [UIView beginAnimations:@"Curl"context:nil];//动画开始
        [UIView setAnimationDuration:0.40];
        [UIView setAnimationDelegate:self];
        [moveLine setFrame:frame];
        [UIView commitAnimations];
    }
}
/*****************************************环信设置start***********************************************************/
/*****************************************环信设置start***********************************************************/
#pragma mark 环信相关设置
-(void)huanxinSet{
    
    //获取未读消息数，此时并没有把self注册为SDK的delegate，读取出的未读数是上次退出程序时的
    [self didUnreadMessagesCountChanged];
#warning 把self注册为SDK的delegate
    [self registerNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUntreatedApplyCount) name:@"setupUntreatedApplyCount" object:nil];
    
    [self setupSubviews];
    
    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [addButton setImage:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addFriendAction) forControlEvents:UIControlEventTouchUpInside];
    _addFriendItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    [self setupUnreadMessageCount];
    [self setupUntreatedApplyCount];

}

- (void)dealloc
{
    [self unregisterNotifications];
}

#pragma mark - private

-(void)registerNotifications
{
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications
{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)setupSubviews
{
    
}

-(void)unSelectedTapTabBarItems:(UITabBarItem *)tabBarItem
{
    [tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                        [UIFont systemFontOfSize:14], UITextAttributeFont,[UIColor whiteColor],UITextAttributeTextColor,
                                        nil] forState:UIControlStateNormal];
}

-(void)selectedTapTabBarItems:(UITabBarItem *)tabBarItem
{
    [tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                        [UIFont systemFontOfSize:14],
                                        UITextAttributeFont,[UIColor colorWithRed:0.393 green:0.553 blue:1.000 alpha:1.000],UITextAttributeTextColor,
                                        nil] forState:UIControlStateSelected];
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    NSLog(@"未读消息数目:unreadCount = %i",unreadCount);
    NSString * unreadCountStr = unreadCount>0?@"highlighted":@"normal";
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationUnreadChatMsgRefreshed object:unreadCountStr];
    self.leveyTabBarController.tabBarItem.badgeValue = @"10";
    self.tabBarItem.badgeValue = @"11";
    /* 设置未读条数
    if (_chatListVC) {
        if (unreadCount > 0) {
            _chatListVC.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unreadCount];
        }else{
            _chatListVC.tabBarItem.badgeValue = nil;
        }
    }
    */
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
}

- (void)setupUntreatedApplyCount
{
    self.tabBarItem.badgeValue = @"1222";
    NSInteger unreadCount = [[[ApplyViewController shareController] dataSource] count];
    NSLog(@"未处理申请数目:unreadCount = %i",unreadCount);
    /*设置未处理申请数目
    if (_contactsVC) {
        if (unreadCount > 0) {
            _contactsVC.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unreadCount];
        } else {
            _contactsVC.tabBarItem.badgeValue = nil;
        }
    }
    */
}

#pragma mark - IChatManagerDelegate 消息变化
- (void)didUpdateConversationList:(NSArray *)conversationList
{
    /* 获取离线消息
    [_chatListVC refreshDataSource];
     */
}

// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    [self setupUnreadMessageCount];
}

- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages{
    [self setupUnreadMessageCount];
}

- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupList];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    
    if (ret) {
        EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
        
        do {
            if (options.noDisturbing) {
                NSDate *now = [NSDate date];
                NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour | NSCalendarUnitMinute
                                                                               fromDate:now];
                
                NSInteger hour = [components hour];
                //        NSInteger minute= [components minute];
                
                NSUInteger startH = options.noDisturbingStartH;
                NSUInteger endH = options.noDisturbingEndH;
                if (startH>endH) {
                    endH += 24;
                }
                
                if (hour>=startH && hour<=endH) {
                    ret = NO;
                    break;
                }
            }
        } while (0);
    }
    
    return ret;
}

// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    BOOL needShowNotification = message.isGroup ? [self needShowNotification:message.conversation.chatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        [self playSoundAndVibration];
        
        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
        if (!isAppActivity) {
            [self showNotificationWithMessage:message];
        }
#endif
    }
}

- (void)playSoundAndVibration{
    
    //如果距离上次响铃和震动时间太短, 则跳过响铃
    NSLog(@"%@, %@", [NSDate date], self.lastPlaySoundDate);
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        return;
    }
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EaseMob sharedInstance].deviceManager asyncPlayNewMessageSound];
    // 收到消息时，震动
    [[EaseMob sharedInstance].deviceManager asyncPlayVibration];
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = @"[图片]";
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = @"[位置]";
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = @"[音频]";
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = @"[视频]";
            }
                break;
            default:
                break;
        }
        
        NSString *title = message.from;
        if (message.isGroup) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:message.conversation.chatter]) {
                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                    break;
                }
            }
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = @"您有一条新消息";
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = @"打开";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    //    UIApplication *application = [UIApplication sharedApplication];
    //    application.applicationIconBadgeNumber += 1;
}

#pragma mark - IChatManagerDelegate 登陆回调（主要用于监听自动登录是否成功）

- (void)didLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error
{
    if (error) {
        
        NSString *hintText = @"你的账号登录失败，正在重试中... \n点击 '登出' 按钮跳转到登录页面 \n点击 '继续等待' 按钮等待重连成功";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:hintText
                                                            delegate:self
                                                            cancelButtonTitle:@"继续等待"
                                                            otherButtonTitles:@"登出",
                                                            nil];
        alertView.tag = 99;
        [alertView show];
    }
}

#pragma mark - IChatManagerDelegate 好友变化

- (void)didReceiveBuddyRequest:(NSString *)username
                       message:(NSString *)message
{
#if !TARGET_IPHONE_SIMULATOR
    [self playSoundAndVibration];
    
    BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
    if (!isAppActivity) {
        //发送本地推送
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date]; //触发通知的时间
        notification.alertBody = [NSString stringWithFormat:@"%@ %@", username, @"添加你为好友"];
        notification.alertAction = @"打开";
        notification.timeZone = [NSTimeZone defaultTimeZone];
    }
#endif
    
//    [_groupsTableView reloadApplyView];
}

- (void)didUpdateBuddyList:(NSArray *)buddyList
            changedBuddies:(NSArray *)changedBuddies
                     isAdd:(BOOL)isAdd
{
    [_groupsTableView reloadDataSource];
}

- (void)didRemovedByBuddy:(NSString *)username
{
    [[EaseMob sharedInstance].chatManager removeConversationByChatter:username deleteMessages:YES];
    [_friendsTableView refreshDataSource];
    [_groupsTableView reloadDataSource];
}

- (void)didAcceptedByBuddy:(NSString *)username
{
    [_groupsTableView reloadDataSource];
}

- (void)didRejectedByBuddy:(NSString *)username
{
    NSString *message = [NSString stringWithFormat:@"你被'%@'拒绝了", username];
    TTAlertNoTitle(message);
}

- (void)didAcceptBuddySucceed:(NSString *)username{
    [_groupsTableView reloadDataSource];
}

#pragma mark - IChatManagerDelegate 群组变化

- (void)didReceiveGroupInvitationFrom:(NSString *)groupId
                              inviter:(NSString *)username
                              message:(NSString *)message
{
#if !TARGET_IPHONE_SIMULATOR
    [self playSoundAndVibration];
#endif
    
//    [_groupsTableView reloadGroupView];
}

//接收到入群申请
- (void)didReceiveApplyToJoinGroup:(NSString *)groupId
                         groupname:(NSString *)groupname
                     applyUsername:(NSString *)username
                            reason:(NSString *)reason
                             error:(EMError *)error
{
    if (!error) {
#if !TARGET_IPHONE_SIMULATOR
        [self playSoundAndVibration];
#endif
        
//        [_groupsTableView reloadGroupView];
    }
}

- (void)didReceiveGroupRejectFrom:(NSString *)groupId
                          invitee:(NSString *)username
                           reason:(NSString *)reason
{
    NSString *message = [NSString stringWithFormat:@"你被'%@'拒绝了", username];
    TTAlertNoTitle(message);
}


- (void)didReceiveAcceptApplyToJoinGroup:(NSString *)groupId
                               groupname:(NSString *)groupname
{
    NSString *message = [NSString stringWithFormat:@"同意加入讨论组\'%@\'", groupname];
    [self showHint:message];
}

#pragma mark - IChatManagerDelegate 登录状态变化

- (void)didLoginFromOtherDevice
{
    __weak CommunicationViewController *weakSelf = self;
    
    [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
        
        [WCAlertView showAlertWithTitle:@"提示" message:@"你的账号已在其他地方登录" customizationBlock:nil completionBlock:
         ^(NSUInteger buttonIndex, WCAlertView *alertView) {
             if (buttonIndex == 0) {
                 NSUserDefaults * defaultData = [NSUserDefaults standardUserDefaults];
                 [defaultData setBool:NO forKey:@"login"];
                 [defaultData synchronize];
//                 [self logoutAction];
                 
                 [self showHudInView:self.view hint:@"正在退出..."];
                 [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
                     [weakSelf hideHud];
                     if (error) {
                         NSLog(@"退出失败!");
                         NSLog(@"退出交流error.description = %@",error.description);
                         [weakSelf showHint:error.description];
                     } else {
                         //            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                         NSLog(@"退出成功!");
                         [[ApplyViewController shareController] clear];
                         [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
                     }
                 } onQueue:nil];
                 
             }
         } cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        

        
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
//                                                            message:@"你的账号已在其他地方登录"
//                                                           delegate:self
//                                                  cancelButtonTitle:@"确定"
//                                                  otherButtonTitles:nil,
//                                  nil];
//        alertView.tag = 100;
//        [alertView show];
    } onQueue:nil];
}

- (void)logoutAction
{
    __weak CommunicationViewController *weakSelf = self;
    [self showHudInView:self.view hint:@"正在退出..."];
    [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
        [weakSelf hideHud];
        if (error) {
            NSLog(@"退出失败!");
            NSLog(@"退出交流error.description = %@",error.description);
            [weakSelf showHint:error.description];
        } else {
            //            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
            NSLog(@"退出成功!");
            [[ApplyViewController shareController] clear];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
        }
    } onQueue:nil];
}

- (void)didRemovedFromServer {
    [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"你的账号已被从服务器端移除"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil,
                                                                   nil];
        alertView.tag = 101;
        [alertView show];
    } onQueue:nil];
}

- (void)didConnectionStateChanged:(EMConnectionState)connectionState
{
    [_friendsTableView networkChanged:connectionState];
}

#pragma mark -

- (void)willAutoReconnect{
    [self hideHud];
    [self showHudInView:self.view hint:@"正在重连中..."];
}

- (void)didAutoReconnectFinishedWithError:(NSError *)error{
    [self hideHud];
    if (error) {
        [self showHint:@"交流重连失败，稍候将继续重连"];
    } else {
//        [self showHint:@"重连成功！"];
    }
}

#pragma mark - public

- (void)jumpToChatList
{
    if(_friendsTableView)
    {
        [self.navigationController popToViewController:self animated:NO];
//        [self setSelectedViewController:_friendsTableView];
        [self switchPageVc2:1];
    }
}


/*****************************************环信设置end***********************************************************/
/*****************************************环信设置end***********************************************************/
-(void)viewWillAppear:(BOOL)animated{
    [self.leveyTabBarController.navigationItem setTitle:@"交流"];
    [self.leveyTabBarController.navigationItem setLeftBarButtonItem:nil];
    [self.leveyTabBarController.navigationItem  setRightBarButtonItem:nil];
    
    //获取离线消息
    [_friendsTableView refreshDataSource];
    
    if (_btnTag == 1003 ) {
        
    }
}

-(void)getAddressBookFromNet
{
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:API_BASE_URL(@"/ScienceApp/ieaction.do")];
    [request setPostValue:@"getChatList" forKey:@"type"];
    
    NSDictionary * dict =  [[NSUserDefaults standardUserDefaults] objectForKey:@"personalInfo"];
    [request setPostValue:dict[@"institute"] forKey:@"institute"];
    //测试
//    [request setPostValue:@"002" forKey:@"institute"];
    
    [request setDelegate:self];
    [request setTimeOutSeconds:5.0f];
    [request setDidFinishSelector:@selector(requestSuccess:)];
    [request setDidFailSelector:@selector(requestError:)];
    [request startAsynchronous];
}

-(void)requestError:(ASIFormDataRequest *)request{
    [Alert showAlert:@"网络错误!"];
    [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
}

-(void)requestSuccess:(ASIFormDataRequest*)request{
    NSData* requestData = [request.responseString  dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *userArr = [NSJSONSerialization JSONObjectWithData:requestData  options:NSJSONReadingMutableLeaves error:nil];
    [_addrsTableView.view removeFromSuperview];
    users=[NSMutableArray arrayWithCapacity:0];
    
    if (!_context) {
        return;
    }else{
        [CoreDataEntity sharedCoreDataEntity].context = _context;
    }
    
    NSDictionary * dict =  [[NSUserDefaults standardUserDefaults] objectForKey:@"personalInfo"];
    for (int i=0; i<userArr.count; i++) {
        NSMutableArray *user=[NSMutableArray arrayWithCapacity:0];
        NSDictionary *infoDic = userArr[i][@"info"];
        
        //只保存本学院的党员通讯录信息
//        if(![userArr[i][@"instiNO"] isEqualToString:dict[@"institute"]]) break;
        
        /*保存学院 start*/
        NSDictionary *branchDic = @{
                                    @"instiNO":userArr[i][@"instiNO"],
                                    @"institute":userArr[i][@"institute"]
                                    };
        [CoreDataEntity branchEntityFromDictionary:branchDic context:_context];
//        BranchEntity * branchEntity = [CoreDataEntity branchEntityFromDictionary:branchDic context:_context];
//        [CoreDataEntity saveNewBranch:branchEntity context:_context];
        /*保存学院 end*/
        for (int j =0; j<infoDic.count; j++) {
            NSMutableArray *userInfo=[NSMutableArray arrayWithCapacity:0];
            NSString *brachName = [NSString stringWithFormat:@"branchInfo%i",j+1];
            NSArray *memberArr = [NSArray arrayWithArray:[infoDic objectForKey:brachName][@"member"]];
            /*保存党支部 start*/
            NSDictionary * subPartyDic = @{@"partyNo":[infoDic objectForKey:brachName][@"partyNo"],
                                           @"partyName":[infoDic objectForKey:brachName][@"partyName"],
                                           @"instiNO":userArr[i][@"instiNO"]};
            
            [CoreDataEntity subPartyEntityFromDictionary:subPartyDic context:_context];
//            SubPartyEntity * subParty = [CoreDataEntity subPartyEntityFromDictionary:subPartyDic context:_context];
//            [CoreDataEntity saveNewSubParty:subParty context:_context];
            
            /*保存党支部 end*/
            NSLog(@"memberArr.count = %i",memberArr.count);
            for (int k=0; k<memberArr.count; k++) {
                //将一个字典中的velue和key添加到另外一个字典中
                RADataObject *node3 = [RADataObject dataObjectWithName:memberArr[k][@"name"] userId:memberArr[k][@"userID"] headUrl:memberArr[k][@"headUrl"]  children:nil];
                [userInfo addObject:node3];
                
                NSDictionary *d = [self createUserDict:memberArr[k]];
                NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:d];
                [dic setObject:userArr[i][@"instiNO"] forKey:@"instiNo"];
                [dic setObject:brachName forKey:@"branchInfo"];
                [dic setObject:[infoDic objectForKey:brachName][@"partyName"] forKey:@"partyName"];
                [dic setObject:[infoDic objectForKey:brachName][@"partyNo"] forKey:@"partyNo"];
                
                [CoreDataEntity userFromDictionary:dic context:_context];
//                UserInfoEntity * userInfo = [CoreDataEntity userFromDictionary:dic context:_context];
//                 if (![CoreDataEntity haveSaveUserByUserId:userInfo.userID context:context]){
//                   [CoreDataEntity saveNewUserInfo:userInfo context:context];
//                   [[NSNotificationCenter defaultCenter]postNotificationName:kXMPPNewFriendNotifaction object:nil userInfo:nil];
//                 }
//                 [CoreDataEntity saveNewUserInfo:userInfo context:_context];
            }
            
            
            RADataObject *node2 = [RADataObject dataObjectWithName:[infoDic objectForKey:brachName][@"partyName"] userId:nil  headUrl:nil children:[NSArray arrayWithArray:userInfo]];
            [user addObject:node2];
            userInfo= nil;
        }
        RADataObject *node1 = [RADataObject dataObjectWithName:userArr[i][@"institute"] userId:nil  headUrl:nil  children:[NSArray arrayWithArray:user]];
        [users insertObject:node1 atIndex:users.count];
//        _addrsTableView = [[RAViewController alloc] initWithNibName:@"RAViewController_iPhone" bundle:nil withArray:users];
        _addrsTableView = [[RAViewController alloc] initWithArray:users];
        user = nil;

    }
    
    NSError * error;
    if ([_context save:&error]) {
        NSLog(@"新增记录成功!");
        //清除指示器
         [_addrsTableView.view  setFrame:CGRectMake(_width, -35, _width, [[UIScreen mainScreen] bounds].size.height-125)];
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        [_scrollView addSubview:_addrsTableView.view];
    } else {
         NSLog(@"新增记录失败!");
        [Alert showAlert:@"通讯录加载失败"];
    }
}

-(void)getAddressBookFromLocal
{
    //显示指示器
    MBProgressHUD * hud  = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    hud.labelText = @"通讯录加载中";
    hud.labelFont = [UIFont systemFontOfSize:15];
    hud.dimBackground = YES;
    
    users=[NSMutableArray arrayWithCapacity:0];
    
    BOOL result = [CoreDataEntity haveCreateBranchAndSubPartyWithContext:_context];

    if (result) {//说明通讯录列表已经下载在本地了
        
        NSLog(@"从本地获取通讯录!");
        //        NSMutableArray *user=[NSMutableArray arrayWithCapacity:0];
        //1.获取学院列表
        NSArray * branchArr = [CoreDataEntity fetchAllBranchsWithContext:_context];
        //2.以instiNo为条件获取每个学院所包含的支部列表
        for (BranchEntity * branch in branchArr) {
            NSMutableArray *user=[NSMutableArray arrayWithCapacity:0];
            NSArray * subPartyArr = [CoreDataEntity getSubPartyByInstiNo:branch.instituteNo context:_context];
            
            for (SubPartyEntity * subParty in subPartyArr) {
                NSArray * friendsArr = [CoreDataEntity getUsersByPartyNo:subParty.partyNo context:_context];
                NSMutableArray *userInfo=[NSMutableArray arrayWithCapacity:0];
                for (UserInfoEntity * userObject in friendsArr) {
                    RADataObject *node3 = [RADataObject dataObjectWithName:userObject.name userId:userObject.userID headUrl:userObject.headUrl  children:nil];
                    [userInfo addObject:node3];
                }
                RADataObject *node2 = [RADataObject dataObjectWithName:subParty.partyName userId:nil headUrl:nil  children:[NSArray arrayWithArray:userInfo]];
                [user addObject:node2];
            }
            RADataObject *node1 = [RADataObject dataObjectWithName:branch.instituteName  userId:nil headUrl:nil children:[NSArray arrayWithArray:user]];
            [users insertObject:node1 atIndex:users.count];
//            _addrsTableView = [[RAViewController alloc] initWithNibName:@"RAViewController_iPhone" bundle:nil withArray:users];
            _addrsTableView = [[RAViewController alloc] initWithArray:users];
            user = nil;
        }
        //清除指示器
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        NSLog(@"从本地获取通讯录成功!");
        return;
    }
    NSLog(@"首次启动程序,需要下载通信录!");
    
    //从网络上获取通信录
    [self getAddressBookFromNet];
}

-(NSDictionary *)createUserDict:(NSDictionary *) memberDic{
    NSDictionary *dic=@{
                        @"userId":memberDic[@"userName"]
                        ,@"userNickname":memberDic[@"name"]
                        ,@"userDescription":memberDic[@"userName"]
                        ,@"userHead":memberDic[@"zipHeadUrl"]
                        ,@"timeCreate":memberDic[@"partyTime"]
                        ,@"roomFlag":[NSNumber numberWithInt:0]
                        ,@"newMsgs":[NSNumber numberWithInt:0]
                        ,@"branch":memberDic[@"branch"]
                        ,@"headUrl":memberDic[@"headUrl"]
                        ,@"name":memberDic[@"name"]
                        ,@"userID":memberDic[@"userID"]
                        ,@"userName":memberDic[@"userName"]
                        };
    return dic;
}
@end
